/*eslint-disable*/

export default {
    // 根据长边检查图片是否需要横竖转置
    checkAndTransposeImage(base64Data, callback) {
        // 创建Image对象
        var img = new Image();

        // 设置Image对象的src属性为base64编码的图像数据
        img.src = "data:image/png;base64," + base64Data;

        // 图像加载完成后执行回调函数
        img.onload = function () {
            // 获取图像的宽度和高度
            var width = this.width;
            var height = this.height;

            // 判断是否需要横竖转置
            var needTranspose = height > width;

            // 在这里可以执行根据需要转置的逻辑
            if (needTranspose) {
                // 使用Canvas执行横竖转置的操作
                var canvas = document.createElement("canvas");
                var ctx = canvas.getContext("2d");

                canvas.width = img.height;
                canvas.height = img.width;

                // 画布中心点平移至中心(0,0)->(x,y)
                ctx.translate(canvas.width / 2, canvas.height / 2);
                // 画布旋转270°
                ctx.rotate(270 * Math.PI / 180);
                // 绘制图像 图像起始点需偏移负宽高
                ctx.drawImage(img, -img.width / 2, -img.height / 2);

                // 替换原始图像
                let url = canvas.toDataURL()
                callback(url)
            }
            else {
                callback("data:image/png;base64," + base64Data)
            }
        };

        // 图像加载失败时执行的回调函数
        img.onerror = function () {
            console.error("Error loading image");
        };
    },
    // 褪色
    fadeColor(rgbColor, fadeFactor) {
        // 解析RGB颜色
        const match = rgbColor.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);

        if (!match) {
            throw new Error("Invalid RGB color format");
        }

        // 提取颜色通道的值
        const [, red, green, blue] = match.map(Number);

        // 淡化每个通道的值
        const fadedRed = Math.floor(red * fadeFactor);
        const fadedGreen = Math.floor(green * fadeFactor);
        const fadedBlue = Math.floor(blue * fadeFactor);

        // 构建淡化后的颜色字符串
        const fadedColor = `rgb(${fadedRed}, ${fadedGreen}, ${fadedBlue})`;

        return fadedColor;
    },
    // rgb文字拆分为rgb数值
    extractRGBValues(rgbText) {
        // 使用正则表达式匹配 RGB 文本格式
        const match = rgbText.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);

        if (!match) {
            throw new Error("Invalid RGB color format");
        }

        // 提取匹配的数值
        const [, r, g, b] = match.map(Number);

        // 返回提取的数值
        return { r, g, b };
    },
    // 检测是否过于接近白色或黄色
    CloseToWhiteOrYellow(color) {
        let whiteReference = 200
        let yellowReference = 230
        return (
            (color.r > whiteReference &&
                color.g > whiteReference &&
                color.b > whiteReference) ||
            (color.r > yellowReference && color.g > yellowReference)
        );
    },
    // 提取主色
    extractbgColor(image, pic) {
        return new Promise((res, rej) => {
            const canvas = document.createElement("canvas");
            const ctx = canvas.getContext("2d");

            canvas.width = image.width;
            canvas.height = image.height;

            ctx.drawImage(image, 0, 0, image.width, image.height);

            const imageData = ctx.getImageData(0, 0, image.width, image.height).data;

            // 找到最常见的颜色
            const colorCounts = {};
            let maxCount = 0;
            let dominantColor = null;

            for (let i = 0; i < imageData.length; i += 4) {
                if (
                    imageData[i] < 255 &&
                    imageData[i + 1] < 255 &&
                    imageData[i + 2] < 255
                ) {
                    const color = `rgb(${imageData[i]}, ${imageData[i + 1]}, ${imageData[i + 2]
                        })`;
                    if (color != "rgb(0, 0, 0)") {
                        colorCounts[color] = (colorCounts[color] || 0) + 1;

                        // if (colorCounts[color] > maxCount) {
                        //   maxCount = colorCounts[color];
                        //   dominantColor = color;
                        // }
                    }
                }
            }

            // 将颜色计数对象转换为数组并按出现次数降序排序
            const sortedColors = Object.entries(colorCounts).sort(
                (a, b) => b[1] - a[1]
            );

            // 取出前n多的颜色及其出现次数
            const topColors = sortedColors.slice(0, 10);

            // 计算权重总和
            const totalWeight = topColors.reduce((sum, color) => sum + color[1], 0);

            // 计算加权平均颜色
            let averageColor = [0, 0, 0, 0]; // 初始颜色值，RGBA格式

            topColors.forEach((color) => {
                const weight = color[1] / totalWeight; // 计算权重
                const rgbValues = color[0].match(/\d+/g).map(Number); // 提取RGB值
                averageColor = averageColor.map(
                    (value, index) => value + rgbValues[index] * weight
                ); // 加权求和
            });

            // 输出加权平均颜色
            averageColor = averageColor.map((value) => Math.round(value)); // 四舍五入取整
            dominantColor =
                "rgb(" +
                averageColor[0] +
                "," +
                averageColor[1] +
                "," +
                averageColor[2] +
                ")";

            // 褪色系数
            let fadeFactor = 1.5

            // 背景色
            let finalColor = this.fadeColor(dominantColor, fadeFactor);
            // console.log(dominantColor, finalColor, pic);
            // console.log(dominantColor, topColors, pic);
            pic.bgColor = finalColor;
            // 字体颜色
            let rgbObject = this.extractRGBValues(finalColor);
            pic.fontColor = this.CloseToWhiteOrYellow(rgbObject)
                ? "#212121"
                : "white";
            // 详情背景色
            pic.detailBgColor = finalColor + ",rgba(0,0,0,0)";
            res()
        })
    },
}